package com.ruoyi.common.utils;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.domain.AjaxResult;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class AjaxUtils {
    private final CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config()).build();

    public RequestConfig config() {
        RequestConfig.Builder builder = RequestConfig.custom();
        return builder.setConnectTimeout(1000)
                .setConnectionRequestTimeout(500)
                .setSocketTimeout(10000)
                .setStaleConnectionCheckEnabled(true).build();
    }

    public AjaxResult doGet(String url) throws Exception {
        // 声明 http get 请求
        HttpGet httpGet = new HttpGet(url);
        // 装载配置信息
        httpGet.setConfig(config());
        // 允许重定向
        httpGet.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpGet);
        // 返回响应代码与内容
        return AjaxResult.success("success", JSON.parse(EntityUtils.toString(response.getEntity(), "UTF-8")));
    }

    public AjaxResult doGetWithParams(String url, Map<String, Object> mapParams) throws Exception {
        // 包装URL
        URIBuilder uriBuilder = new URIBuilder(url);
        if (mapParams != null) {
            // 遍历map,拼接请求参数
            for (Map.Entry<String, Object> entry : mapParams.entrySet()) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }
        // 调用不带参数的get请求
        return this.doGet(uriBuilder.build().toString());
    }

    public AjaxResult doPost(String url) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);

        // 加入配置信息
        httpPost.setConfig(config());

        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpPost);
        // 返回响应代码与内容
        return AjaxResult.success("success", JSON.parse(EntityUtils.toString(
                response.getEntity(), "UTF-8")));
    }

    public AjaxResult doPostWithParams(String url, Map<String, Object> params) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config());
        // 判断map是否为空，不为空则进行遍历，封装from表单对象
        if (params != null) {
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
            // 构造from表单对象
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");
            // 把表单放到post里
            httpPost.setEntity(urlEncodedFormEntity);
        }
        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpPost);
        // 返回响应代码与内容
        return AjaxResult.success("success", JSON.parse(EntityUtils.toString(
                response.getEntity(), "UTF-8")));
    }

    /**
     * Json格式的请求
     *
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public AjaxResult doPostWithJsonParams(String url, Map<String, Object> params) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        // 加入配置信息
        httpPost.setConfig(config());
        // 判断map是否为空，不为空则进行遍历，封装from表单对象
        if (params != null) {
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
            // 构造from表单对象
            StringEntity stringEntity = new StringEntity(JSON.toJSONString(list), "UTF-8");
            stringEntity.setContentType("text/json");
            // 把表单放到post里
            httpPost.setEntity(stringEntity);
        }
        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpPost);
        // 返回响应代码与内容
        return AjaxResult.success("success", JSON.parse(EntityUtils.toString(
                response.getEntity(), "UTF-8")));
    }

}
